package com.niiwoo.civet.trade.listener;

import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.service.local.lend.ProjectLendLocalService;
import com.niiwoo.tripod.provider.exception.BizException;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ProjectLendListener {

	private static final Logger logger = LoggerFactory.getLogger(ProjectLendListener.class);
	
    @Autowired
    private ProjectLendLocalService projectLendLocalService;
    
    @RabbitListener(queues = {MqConstant.PROJECT_LEND_CONTRACT_QUEUE})
    public void projectLendContractHandler(Long projectId, Message message, Channel channel) throws IOException {
        //应答标记
        Boolean isAck = true;
        try {
        	logger.info("projectLendContractHandler projectId:{}",projectId);
            projectLendLocalService.lendContractHandler(projectId);
        } catch (BizException e) {
        	logger.error("projectLendContractHandlerBizException", e);
        } catch (Exception e) {
        	logger.error("projectLendContractHandlerException", e);
            isAck = false;
	        try {
		        Thread.sleep(5 * 1000);
	        } catch (Exception expect) {
	        }
        } finally {
            if (isAck) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }

}
